package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;
import java.util.List;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.HttpTestManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.Task.HttpTask;
import cc.ufinity.networkdiagnose.view.R;

public class HttpTestWidgetProxy extends GeneralTestWidget {
	private HttpTestManager httpTestManager;
	private Activity ctx;
	private Task task;
	private HttpTask httpTask;
	private Button btnBack;
	private Handler httpTestHandler;
	private int taskSize;
	private int currentTaskNum;
	private boolean taskProcessing;
	private int testedTimes;
	public static int testFlag = 0;
    public static int taskFlag = 0;  
	// private static final int COUNT = 3;
	
	private boolean isFirst = true;
	private Handler handlerChild;

	private static final String TAG = "httpTest";
	
	public HttpTestWidgetProxy(Activity context, Handler handl) {
		super(context);
		inflate(context, R.layout.http_test_widget_proxy, this);
		this.ctx = context;
		this.handlerChild = handl;
		btnBack = (Button) this.findViewById(R.id.http_test_proxy_btnBack);

		btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				backToTask(ctx);
			}
		});

		// 定义HTTP 测试句柄，获得每次测试结果
		httpTestHandler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.DONE: //测试完成
					dismissMessageDialog();
					//mSendBroadcast(ctx);
					handlerSendToTarget(handlerChild, MessageWhat.HANDLER_HTTP);
					finishPerTask();
					break;
				case MessageWhat.DO_NEXT_TEST:
					//doFtpTest();
					break;
				default:
					updateHttpTestResult(msg.what);
				}
			}
		};
		httpTestManager = new HttpTestManager(ctx);
		httpTestManager.setHandler(httpTestHandler);
		task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK); 
		startHttpTest();
	}

	public void startHttpTest() {
		if (NetworkManager.detectNetworkConnectivity(ctx) == -1) {
			showMessage(ctx, "无法连接至因特网.");
			return;
		}
		final List<HttpTask> l = task.httpTasks;
		taskSize = l.size();
	 //	showProgressDialog(ctx, "正在进行HTTP测试...", task.testCount*taskSize);
		new Thread() {
			public void run() {
				while (currentTaskNum < taskSize) {
					if (!taskProcessing) {
						httpTask = l.get(currentTaskNum);
						currentTaskNum ++;
						taskProcessing = true;
						httpTestManager.startHttpTest(httpTask.address, task.testCount);
					}
				}
				if (currentTaskNum == taskSize) {
					httpTestManager.sendMsg(MessageWhat.TASK_FINISHED);
				}
			}
		}.start();
	}

	private void finishPerTask() {
		DecimalFormat df = new DecimalFormat("#0.000");
		// int times = httpTestManager.getXdata().length;
		int times = task.testCount;
		long size = httpTestManager.getPageLength();
		float delay = (float) httpTestManager.totalDelayTime / times;
		float speed = (delay == 0) ? 0 : ((float) size * 1000 / 1024)/delay ;
		// Log.e("", String.valueOf(size));
		httpTask.delay = df.format((float) delay / 1000);
		httpTask.speed = df.format(speed * 8);
		httpTask.failedTimes = httpTestManager.failedTimes;
		task.httpTasks.set(currentTaskNum - 1, httpTask);
		
		task.httpAnwerDelay = httpTask.delay;
		task.httpCallCount = times + "";
		int sc = (times - httpTask.failedTimes)<0? 0:(times - httpTask.failedTimes);
		task.httpCallSuccessCount = sc+"";
		task.httpCallSuccessRate = df.format((sc*100)/(float)times);
		// Log.e("Test", "task:" + task.httpTasks.get(0).speed);

		
System.out.println("task.httpAnwerDelay => " + task.httpAnwerDelay);
System.out.println("task.httpCallCount => " + task.httpCallCount);
System.out.println("task.httpCallSuccessCount => " + task.httpCallSuccessCount);
System.out.println("task.httpCallSuccessRate => " + task.httpCallSuccessRate);
		
		
	//----------------------------------------------------------
		GlobalApp.result_HTTP_test.append("\n测试次数=").append(times)
				.append("\n平均时延=").append(httpTask.delay).append(" s")
				.append("\n平均下载速率=").append(httpTask.speed).append(" Kb/s\n");
		
	//----------------------------------------------------------
		taskProcessing = false;
		httpTestManager.processing = false;
		httpTestManager.currentTime = 0;
		httpTestManager.delayTime = 0;
		httpTestManager.totalDelayTime = 0;
	}

	private void updateHttpTestResult(int what) {
		//----------------------------------------------------------
		if(isFirst) {
			isFirst = false;
			StringBuffer temp = new StringBuffer();
			GlobalApp.result_HTTP_test = temp;
		}
	//----------------------------------------------------------
		testedTimes++;
		this.setDialogProgress(testedTimes);
		DecimalFormat df = new DecimalFormat("#0.000");
		StringBuffer sb = null;
		httpTestManager.processing = false;
		int currentTime = httpTestManager.getCurrentTime();
		if (what == MessageWhat.HTTP_PAGELOAD_SUCCESS) {
			long delayTime = httpTestManager.getDelayTime();
			sb = new StringBuffer();
			sb.append("第").append(currentTime).append("次 ")
					.append(httpTestManager.getAddress()).append(" 页面访问时延：")
					.append(df.format(delayTime / (float) 1000)).append(" s");
			//----------------------------------------------------------
			
			GlobalApp.result_HTTP_test.append("第").append(currentTime).append("次 ")
				.append(httpTestManager.getAddress()).append("\n页面访问时延：")
				.append(df.format(delayTime / (float) 1000)).append(" s\n");
			
		//----------------------------------------------------------
		} else if (what == MessageWhat.HTTP_PAGELOAD_FAILED) {
			httpTestManager.failedTimes ++;
			sb = new StringBuffer();
			sb.append("第").append(currentTime).append("次 ")
					.append(httpTestManager.getAddress()).append(" 页面访问失败.");
			//----------------------------------------------------------
			
			GlobalApp.result_HTTP_test.append("第").append(currentTime).append("次 ")
			.append(httpTestManager.getAddress()).append("\n页面访问失败.\n");
			
		//----------------------------------------------------------
		}
	}
	
}
